import {login,getwxUser,saveWxUser,uploadAwart} from '@/api/login/login.js'
export default {
  namespaced: true,
  state: () => ({
	token:uni.getStorageSync('token'),
	userInfo:JSON.parse(uni.getStorageSync('userInfo')||'{}')
	
  }),

  mutations: {
	 //token 
    SET_TOKEN: (state, token) => {
        state.token = token
    },
	//用户信息
	SET_USERINFO: (state, userInfo) => {
		state.userInfo = userInfo
		uni.setStorageSync('userInfo',JSON.stringify(userInfo))
	},
	
	DEL_TOKEN: (state, token) => {
	    state.token = ''
	},
	DEL_USERINFO: (state, userInfo) => {
		state.userInfo = {}
	},
  },

  // 模块的 mutations 方法
  actions: {
	  //登录
	loginAction({commit,dispatch},payload){
		login(payload.data).then(res=>{
			commit('SET_TOKEN',res.data.token)
			//token保存到本地
			uni.setStorageSync('token',res.data.token)
			
			if(payload.success){
				payload.success(res)
				
			}
			
		})
	},
	//退出微信登录
	unLoginAction({commit,dispatch},payload){
		commit('DEL_TOKEN')
		commit('DEL_USERINFO')
		uni.removeStorageSync('token')
		uni.removeStorageSync('userInfo')
	},
	//更改头像
	updataAvatar({commit,dispatch},payload){
		saveWxUser(payload.data).then(res=>{
			dispatch('getwxUserAction')
			
		})
	},
	//更改昵称
	updataNickName({commit,dispatch},payload){
		saveWxUser(payload.data).then(res=>{
			dispatch('getwxUserAction')
			
		})
	},
	//获取用户信息
	getwxUserAction({commit,dispatch},payload){
		getwxUser().then(res=>{
			if(res.data.code!=200){
				commit('DEL_TOKEN')
				commit('DEL_USERINFO')
			}else{
				commit('SET_USERINFO',res.data.data)
				if(payload){
					payload.success(res)
				}
			}
		})
	},
	//保存用户信息
	saveWxUserAction({commit,dispatch},payload){
		saveWxUser(payload.data).then(res=>{
		dispatch('getwxUserAction')
			
		})
	},
	uploadAwartAction({commit,dispatch},payload){
		if(payload.data){
			uploadAwart(payload.data).then(res=>{
				dispatch('saveWxUserAction',{data:{avatar:res.data.fileName}})
			})
		}
		
	}
	
},

  // 模块的 getters 属性
  getters: {
	
  }
}